package com.gid.rcflightlogger;

import android.content.Context;

import com.orm.androrm.CharField;
import com.orm.androrm.Filter;
import com.orm.androrm.Model;
import com.orm.androrm.QuerySet;

//class used for storing general settings, on retrieval will create new entries if non exist
public class Setting extends Model {
		
	public static final QuerySet<Setting> objects(Context context) {
		return objects(context, Setting.class);
	}

	public static final int DEFAULT_COUNTDOWN = 6 * 60;
	protected CharField mKey;
	protected CharField mValue; // serialized string of everything

	// constructor
	public Setting() {
		super();

		mKey = new CharField();
		mValue = new CharField();
		reset();
	}

	// reset all fields to default value
	public void reset() {
		mKey.set("");
		mValue.set("");
	}

	public String getKey() {
		return mKey.get();
	}

	public void setKey(String key) {
		mKey.set(key);
	}

	public String getValue() {
		return mValue.get();
	}

	public void setValue(String val) {
		mValue.set(val);
	}

	// return settign entry that matches key
	// return null of none found
	private static Setting findSetting(Context context, String key) {
		Filter filter = new Filter();
		filter.is("mKey", key);

		QuerySet<Setting> settings = Setting.objects(context).filter(filter)
				.distinct();
		if (settings.isEmpty()) {
			return null;
		}
		return settings.iterator().next();
	}

	static int getValueForKey(Context context, String key, int default_value) {
		Setting st = findSetting(context, key);
		if (st == null) {
			st = new Setting();
			st.setKey(key);
			st.setValue(Integer.toString(default_value));
			st.save(context);
			return default_value;
		} else {
			try {
				int curr_val = Integer.parseInt(st.getValue());
				return curr_val;
			} catch (NumberFormatException e) {
				st.setValue(Integer.toString(default_value));
				st.save(context);
				return default_value;
			}
		}
	}
	
	static void setValueForKey(Context context, String key, int value) {
		Setting st = findSetting(context, key);
		if (st == null) {
			st = new Setting();
			st.setKey(key);
		}
		st.setValue(Integer.toString(value));
		st.save(context);
	}
}